/**
 * Created by jojo
 */

/**
 * 单图上传
 *
 * @param options
 */
function imageUploader(options) {
    var defaultSetting = {
        urlName: 'default/image',   //用于掺入图片url
        uploaderName: 'uploader1',  //新建plupload对象名
        uploaderBtn: 'm-selectfiles', //上传按钮id
        progressBtn: 'm-ossfile',   //进度条显示块id
        img: 'm-avatar',        //<img>的id
        img2: 'mm-avatar'       //<input>图片url的id
    };

    var option = $.extend(defaultSetting,options);

    set_dirname(option.urlName);
    var uploader1 = option.uploaderName;
    uploader1 = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: option.uploaderBtn,
        multi_selection: false,
        url: 'http://oss.aliyuncs.com',

        init: {
            PostInit: function() {
                document.getElementById(option.progressBtn).innerHTML = '';
            },

            FilesAdded: function(up, files) {
                plupload.each(files, function(file) {
                    var fileName = file.name;
                    var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
                    if (fileExtension !== "jpg" && fileExtension !== "jpeg" && fileExtension !== "gif" && fileExtension !== "png") {
                        toastr.error("图片类型必须是.gif,jpeg,jpg,png中的一种");
                        return;
                    }
                    up.files[0] = file;
                    up.files.splice(1, up.files.length - 1);
                    document.getElementById(option.progressBtn).innerHTML = '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>' +
                        '<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" style="width: 0%"></div></div>' +
                        '</div>';
                });
                set_upload_param(uploader1, '', false);
            },

            BeforeUpload: function(up, file) {
                set_upload_param(up, file.name, true);
            },

            UploadProgress: function(up, file) {
                var d = document.getElementById(file.id);
                d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                var prog = d.getElementsByTagName('div')[0];
                var progBar = prog.getElementsByTagName('div')[0];
                progBar.style.width = file.percent + '%';
                progBar.setAttribute('aria-valuenow', file.percent);
            },

            FileUploaded: function(up, file, info) {
                if (info.status == 200) {
                    $('#' + option.img).attr("src", get_uploaded_object_name());
                    $('#' + option.img2).val(get_uploaded_object_name());
                    toastr.success("上传成功");
                    // 1秒后去除进度条
                    setTimeout(function () {
                        document.getElementById(option.progressBtn).innerHTML = '';
                    },1000)
                } else {
                    toastr.error(info.response);
                }
            },

            Error: function(up, err) {
                toastr.error('上传失败：' + err.response);
            }
        }
    });

    uploader1.init();

}

/**
 * 多图上传
 *
 * @param options
 */
function multipleUploader(options) {
    var defaultSetting = {
        urlName: 'default/image/',      //用于掺入图片url
        uploaderName: 'uploader2',      //新建plupload对象名
        uploaderBtn: 'm-selectfiles',   //上传按钮id
        progressBtn: 'm-ossfile',       //进度条显示块id
        gallery: 'img-gallery',         //图片组的id
        imgId: 'imgId',              //<img>标签id
        colmd:'colmd'                  //daxiao
    };

    var option = $.extend(defaultSetting, options);

    set_dirname(option.urlName);
    var uploader2 = option.uploaderName;

    uploader2 = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: option.uploaderBtn,
        multi_selection: true,
        url: 'http://oss.aliyuncs.com',

        init: {
            PostInit: function () {
                document.getElementById(option.progressBtn).innerHTML = '';
            },

            FilesAdded: function (up, files) {
                plupload.each(files, function (file) {
                    set_upload_param(up, '', false);
                });
            },

            BeforeUpload: function (up, file) {
                set_upload_param(up, file.name, true);
            },


            FileUploaded: function (up, file, info) {
                var fileName = file.name;
                var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
                if (fileExtension !== "jpg" && fileExtension !== "jpeg" && fileExtension !== "gif" && fileExtension !== "png") {
                    toastr.error("图片类型必须是.gif,jpeg,jpg,png中的一种");
                    return;
                }
                if (info.status == 200) {
                    document.getElementById('m-ossfile').innerHTML = '';
                    var html1 = $('#' + option.gallery).html();
                    var html2 =
                        "<div class='col-md-"+option.colmd+" img-item' style='border: 1px solid rgba(86,61,124,.2);margin-left: 15px;margin-bottom: 15px;'>" +
                        "<div class='row'>" +
                        "<div class='col-md-2 no-padding'>" +
                        "<button type='button' class='move pull-right' style='background: rgba(255, 255, 255, 0.3);border: transparent;'><i class='fa fa-angle-double-left'></i></button>" +
                        "</div>" +
                        "<div class='col-md-2 no-padding pull-right'>" +
                        "<button type='button' class='close pull-left' aria-hidden='true' onclick='deleteSelf(this)'>&times;</button>" +
                        "</div>" +
                        "</div>" +
                        "<div class='row m-cover'>" +
                        "<div class='col-md-12 mm-cover no-padding'>" +
                        "<img id='\" + option.imgId + \"' src=" + get_uploaded_object_name(file.name) + " height='100px' width='100%' style='border-top: 1px solid rgba(86,61,124,.2);'>" +
                        "</div>" +
                        "</div>" +
                        "</div>";
                    $('#' + option.gallery).html(html1 + html2);

                    $("#noPic").remove();
                }
                else {
                    toastr.error(info.response);
                }
            },

            Error: function (up, err) {
                toastr.error('上传封面失败：' + err.response);
            }
        }
    });
    uploader2.init();
}

/**
 * 删除选中图片
 *
 * @param obj
 */
function deleteSelf(obj) {
    var parent = $(obj).parent().parent().parent();
    parent.remove();
    if ($("#m-imgGroup").children().length == 0)
    {
        var html =
            "<div class='col-md-2 img-item' id='noPic' style='border: 1px solid rgba(86,61,124,.2);margin-left: 15px;margin-bottom: 15px;'>" +
            "<div class='row'>" +
            "<div class='col-md-2 no-padding'>" +
            "<button type='button' class='move pull-right' style='background: rgba(255, 255, 255, 0.3);border: transparent;'><i class='fa fa-angle-double-left'></i></button>" +
            "</div>" +
            "<div class='col-md-2 no-padding pull-right'>" +
            "<button type='button' class='close pull-left' aria-hidden='true' onclick='deleteSelf(this)'>&times;</button>" +
            "</div>" +
            "</div>" +
            "<div class='row m-cover'>" +
            "<div class='col-md-12 mm-cover no-padding'>" +
            "<img id='\" + option.imgId + \"' src='http://placehold.it/100x100/e6e6e6/e6e6e6' height='100px' width='100%' style='border-top: 1px solid rgba(86,61,124,.2);'>" +
            "</div>" +
            "</div>" +
            "</div>";

        $("#m-imgGroup").html(html)
    }
}

/**
 * 与前一张图片交换位置
 *
 * @param options
 */
function moveToLeft(options) {
    $('#' + options.gallery).on('click', '.move', function (e) {
        e.preventDefault();
        stepOne(this);
    });
}
function stepOne(node) {
    node = $(node).closest('.img-item')
    var $before = $(node).prev(".img-item");
//                alert($before.html());
    if ($before.html() != undefined && $before != undefined && isNotNull($before)) {
        var x = $(node).wrap('<p/>').parent().html();
        $(node).unwrap();
        $(node).remove();
        $(x).insertBefore($before);
    }
}